package test.administrator.example.com.mvptest1.framework.support.manager;

import android.support.annotation.NonNull;
import android.util.ArrayMap;

import java.util.Map;

import test.administrator.example.com.mvptest1.framework.MvpPresenter;

/**
 * Created by thinkpad on 2018/8/2.
 */

public class ActivityScopCache {

	private final Map<String, PresenterHolder> presenterMap = new ArrayMap<String, PresenterHolder>();

	protected ActivityScopCache() {
	}

	/**
	 * 根据指定ID, 得到P
	 */
	public <P> P getPresenter(String viewId) {
		PresenterHolder presenterHolder = presenterMap.get(viewId);
		return presenterHolder == null ? null : (P) presenterHolder.presenter;
	}

	/**
	 * 添加P（缓存P）
	 */
	public void putPresenter(String viewId, MvpPresenter<?> presenter) {
		if (viewId == null) {
			throw new NullPointerException("你的Id为空");
		}
		if (presenter == null) {
			throw new NullPointerException("你的presenter不能为空...");
		}
		PresenterHolder holder = presenterMap.get(viewId);
		if (holder == null) {
			holder = new PresenterHolder();
			holder.presenter = presenter;
			presenterMap.put(viewId, holder);
		} else {
			holder.presenter = presenter;
		}
	}

	/**
	 * 删除指定Id的Presenter
	 *
	 * @param viewId
	 */
	public void remove(String viewId) {
		if (viewId == null) {
			throw new NullPointerException("你的Id为空");
		}
		presenterMap.remove(viewId);
	}

	/**
	 * 清空缓存
	 */
	public void clear() {
		presenterMap.clear();
	}

	private static final class PresenterHolder {
		private MvpPresenter<?> presenter;
		private Object viewState;
	}

	/**
	 * 提供缓存
	 */
	public <VS> VS getViewState(@NonNull String viewId) {
		PresenterHolder holder = presenterMap.get(viewId);
		return holder == null ? null : (VS) holder.viewState;
	}

	/**
	 * 创建
	 *
	 * @param viewId
	 * @param viewState
	 */
	public void putViewState(@NonNull String viewId, @NonNull Object viewState) {
		if (viewId == null) {
			throw new NullPointerException("你的Id为空");
		}
		if (viewState == null) {
			throw new NullPointerException("你的viewState不能为空...");
		}
		PresenterHolder holder = presenterMap.get(viewId);
		if (holder == null) {
			holder = new PresenterHolder();
			holder.viewState = viewState;
			presenterMap.put(viewId, holder);
		} else {
			holder.viewState = viewState;
		}
	}

}
